<template>
  <div class="end_article">
    <div class="app">
      <!-- 头部 -->
      <div class="head">
        <h2>发表新攻略</h2>
        <p>分享你的个人游记，让更多人看到哦！</p>
      </div>
      <!-- 主体内容 -->
      <div class="content">
        <!-- 标题输入框 -->
        <el-input v-model="form.title" placeholder="请输入标题"></el-input>

        <!-- 富文本 -->
        <client-only>
          <VueEditor
            v-model="form.content"
            useCustomImageHandler
            @image-added="handleImageAdded"
            :editorToolbar="customToolbar"
          />
        </client-only>

        <!-- 远程搜索框 -->
        <span>选择城市</span>
        <el-autocomplete
          v-model="cityName"
          :fetch-suggestions="querySearchAsync"
          placeholder="请搜索游玩城市"
          @select="handleSelect"
          :trigger-on-focus="false"
        ></el-autocomplete>
      </div>

      <!-- 按钮 -->
      <div class="bottom">
        <el-button type="primary" @click="publish">发布</el-button>
        <span>
          或者
          <el-button @click="handleDrafts">保存到草稿</el-button>
        </span>
      </div>
    </div>
    <!-- 侧边栏 -->
    <div class="sidebar">
      <h3>草稿箱（{{ $store.state.draftsstore.draftsList.length }}）</h3>
      <div
        class="drafts"
        v-for="(item, index) in $store.state.draftsstore.draftsList"
        :key="index"
      >
        <div>{{ item.title }}</div>
        <span class="date">
          <div>{{ item.date }}</div>
          <span class="icon">
            <i class="el-icon-edit" @click="edit(item, index)"></i>
            <i class="el-icon-delete" @click="del(index)"></i>
          </span>
        </span>
      </div>
    </div>
  </div>
</template>

<script>
import { myrequest } from '~/utils/http'
import axios from '@/utils/http'
export default {
  data() {
    return {
      customToolbar: [
        ['bold', 'italic', 'underline'],
        [{ list: 'ordered' }, { list: 'bullet' }],
        ['image', 'code-block']
      ],
      cityName: '', //用于显示的城市名
      form: {
        title: '',
        city: '',
        content: ''
      }
    }
  },
  methods: {
    // 上传图片，图片预览
    handleImageAdded(file, Editor, cursorLocation, resetUploader) {
      var formData = new FormData()
      formData.append('files', file) //第一个files 后台接收的参数名
      this.$axios({
        url: '/upload', //上传路径
        method: 'POST',
        data: formData
      })
        .then((result) => {
          let url = axios.defaults.baseURL + result.data[0].url // 返回给你的图片路径
          Editor.insertEmbed(cursorLocation, 'image', url)
          resetUploader()
        })
        .catch((err) => {
          console.log(err)
        })
    },
    // 编辑草稿
    edit(item, index) {
      this.form.title = item.title
      this.form.city = item.city
      this.form.content = item.content
      this.cityName = item.cityName
    },
    // 删除草稿
    del(index) {
      this.$confirm('此操作将永久删除该草稿, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then((res) => {
          if (res) {
            this.$store.commit('draftsstore/del', index)
          }
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
        .catch((res) => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 保存草稿
    handleDrafts() {
      // 保存草稿时必须把对象解开，否则会出现双向绑定
      this.$store.commit('draftsstore/addDrafts', {
        title: this.form.title,
        city: this.form.city,
        cityName: this.cityName,
        content: this.form.content,
        date: this.getDate()
      })
      this.$message('保存成功')
    },

    // 发布按钮
    publish() {
      console.log(this.form)
      if (!this.form.title) {
        this.handleMessage('请输入标题！')
        return
      }
      if (!this.form.content) {
        this.handleMessage('请输入文章内容！')
        return
      }
      if (!this.form.city) {
        this.handleMessage('请选择城市！')
        return
      }
      this.$axios({
        url: '/posts',
        method: 'post',
        data: this.form,
        headers: {
          Authorization: 'Bearer ' + this.$store.state.userstore.userInfo.token
        }
      }).then((res) => {
        this.$message(res.data.message)
        if (res.data.message == '新增成功') {
          this.form.title = ''
          this.form.city = ''
          this.form.content = ''
          this.cityName = ''
        }
      })
    },
    // 封装获取城市函数
    async getCityList(name) {
      // 使用正则删除name两端的空格避免报错
      let res = await myrequest('citiesCity', {
        name: name.replace(/(^\s*)|(\s*$)/g, '')
      })
      if (res) {
        const data = res.data.data.map((city) => {
          return { ...city, value: city.name }
        })
        // 返回一个城市列表数组
        return data
      }
    },
    // 输入框value改变时触发
    async querySearchAsync(str, callback) {
      let res = await this.getCityList(str)
      this.form.city = res[0].name
      callback(res)
    },
    // 点击选择城市时触发
    handleSelect(item) {
      this.form.city = item.id
    },
    // 获取日期
    getDate() {
      let myDate = new Date()
      const date = {
        year: myDate.getFullYear(),
        month: myDate.getMonth() + 1,
        day: myDate.getDate()
      }
      return date.year + '-' + date.month + '-' + date.day
    },
    // 提示信息
    handleMessage(name) {
      this.$alert(name, '警告', {
        confirmButtonText: '确定',
        callback: (action) => {
          this.$message({
            type: 'info',
            message: `action: ${action}`
          })
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
.end_article {
  width: 1000px;
  margin: auto;
  display: flex;
  justify-content: space-between;
  .app {
    .head {
      margin-top: 20px;
      h2 {
        font-weight: 400;
      }
      p {
        font-size: 12px;
        color: #999;
        margin: 10px 0;
      }
    }
    .content {
      width: 750px;
      .quillWrapper {
        margin: 20px 0;
      }
    }
    .bottom {
      margin: 20px 0;
    }
  }
  .sidebar {
    margin-top: 20px;
    padding: 10px;
    width: 200px;
    height: 300px;
    border: 1px solid #ccc;
    overflow: hidden;
    h3 {
      font-weight: 400;
    }
    .drafts {
      margin: 5px;
      height: 50px;

      div {
        font-size: 14px;
        overflow: hidden;
        text-overflow: ellipsis;
        -webkit-line-clamp: 2;
        display: -webkit-box;
        -webkit-box-orient: vertical;
      }
      .date {
        font-size: 14px;
        color: #999;
        display: flex;
        justify-content: space-between;
        .icon {
          i {
            margin: 0 5px;
            color: #000;
          }
        }
      }
    }
  }
}
</style>